<script lang="ts" setup>
import { type FormInstance, Message } from '@arco-design/web-vue'
import { ActivityApi } from '@/apis'
import { useForm } from '@/hooks'

const emit = defineEmits(['change'])

const visible = ref(false)
const loading = ref(false)

const id = ref()

const formRef = ref<FormInstance>()
const { form, resetForm } = useForm({
  newUserCouponTemplateId: null,
  newUserCouponCount: 1,
  oldUserCouponTemplateId: null,
  oldUserCouponCount: 1,
})

const rules: FormInstance['rules'] = {
  newUserCouponTemplateId: [{ required: true, message: '请指定新用户赠送优惠券' }],
  newUserCouponCount: [{ required: true, message: '请指定新用户赠送优惠券' }],
  oldUserCouponTemplateId: [{ required: true, message: '请指定老用户赠送优惠券' }],
  oldUserCouponCount: [{ required: true, message: '请指定老用户赠送优惠券数量' }],
}

// 打开编辑
const edit = async (item: ActivityApi.ActivityResp) => {
  id.value = item.id
  const config = JSON.parse(item.config)
  for (const key in form) {
    form[key] = config[key] || form[key]
  }
  console.log('edit: ', form)
  visible.value = true
}

// 保存
const onSave = async () => {
  const isInvalid = await formRef.value?.validate()
  if (isInvalid) {
    return false
  }
  const req = {
    config: JSON.stringify(form),
  }
  await ActivityApi.updateActivity(req, id.value)
  Message.success('修改成功')
  emit('change')
  visible.value = false
  return true
}

// 重置
const reset = () => {
  formRef.value?.resetFields()
  resetForm()
}

defineExpose({ edit })
</script>

<template>
  <ProFormPanel
    v-model:visible="visible"
    mode="drawer"
    title="老带新活动配置"
    :loading="loading"
    :footer="true"
    @confirm="onSave"
    @close="reset"
  >
    <a-form ref="formRef" layout="vertical" :model="form" :rules>
      <a-row :gutter="28">
        <a-form-item label="新用户赠送优惠券" field="newUserCouponTemplateId">
          <CouponTemplateSelect v-model="form.newUserCouponTemplateId" />
        </a-form-item>
        <a-form-item label="新用户赠送优惠券数量" field="newUserCouponCount">
          <a-input-number v-model.trim="form.newUserCouponCount" :min="0" hide-button placeholder="请输入新用户优惠券赠送数量">
            <template #append>
              张
            </template>
          </a-input-number>
        </a-form-item>
        <a-form-item label="老用户赠送优惠券" field="oldUserCouponTemplateId">
          <CouponTemplateSelect v-model="form.oldUserCouponTemplateId" />
        </a-form-item>
        <a-form-item label="新用户赠送优惠券数量" field="oldUserCouponCount">
          <a-input-number v-model.trim="form.oldUserCouponCount" :min="0" hide-button placeholder="请输入老用户优惠券赠送数量">
            <template #append>
              张
            </template>
          </a-input-number>
        </a-form-item>
      </a-row>
    </a-form>
  </ProFormPanel>
</template>

<style lang="less" scoped>

</style>
